package com.tangula.android.kashine.presenter;

import android.content.Context;

import java.util.ArrayList;
import java.util.List;

public abstract class AbstractPaginationPresenter<C extends Context, T>
        extends AbstractPresenter<C> implements PaginationPresenter<T> {

    private int pageIndex = 1;

    private int pageSize = 10;

    private int total;

    private List<T> items = new ArrayList<>();

    public AbstractPaginationPresenter(C context) {
        super(context);
    }

    @Override
    public void onNextPage() {
        if(this.pageSize<1){
            this.pageSize = 10;
        }
        if(this.pageIndex<Math.ceil((float)this.total/(float)this.pageSize)){
            this.pageIndex++;
            this.refresh();
        }
    }

    @Override
    public void onPreviousPage() {
        if(this.pageIndex>1){
            this.pageIndex--;
            this.refresh();
        }
    }

    @Override
    public void onFirstPage() {
        this.pageIndex=1;
        this.refresh();
    }

    @Override
    public void onLastPage() {
        if(this.pageSize<1){
            this.pageSize=10;
        }
        this.pageIndex=(int)Math.ceil((float)pageIndex/(float)pageSize);
        this.refresh();
    }

    @Override
    public int getCurrentPageIndex() {
        return this.pageIndex;
    }

    @Override
    public List<T> getItems() {
        return items;
    }

    @Override
    public int getPageSize() {
        return pageSize;
    }

    @Override
    public int getTotal() {
        return total;
    }

    @Override
    public void setTotal(int total) {
        this.total = total;
    }

    @Override
    public void setPageSize(int ps) {
        this.pageSize = ps;
    }

    @Override
    public void setCurrentPageIndex(int index) {
        this.pageIndex = index;
    }

    @Override
    public void refresh() {
        this.refreshPagination(this.pageIndex, this.pageSize, new PaginationResultHandler<T>(){
            @Override
            public void onSuccess(int index, int pageSize, int total, List<T> records) {
                setCurrentPageIndex(index);
                setPageSize(pageSize>0?pageSize:10);
                setTotal(total);
                items=records;
            }
        }, new ErrorHandler(){
            @Override
            public void onError(Throwable th) {

            }
        });
    }

    protected abstract void refreshPagination(int pageIndex, int pageSize, PaginationResultHandler<T> paginationResultHandler, ErrorHandler errorHandler);

    public interface PaginationResultHandler<R> {
        void onSuccess(int index, int pageSize, int total, List<R> records);
    }

    public interface ErrorHandler{
        void onError(Throwable th);
    }

}
